<template>
  <NModal :show="show" @onUpdateShow="close">
    <div ref="modalRef" class="edit-dia">
      <MacHeader
        :title="title"
        :is-fullscreen="isFullscreen"
        :show-desc="false"
        @toggle="toggle"
        @close="close"
      />
      <div class="content">
        <NScrollbar style="max-height: 80vh">
          <NForm
            ref="formRef"
            :model="queryForm"
            label-placement="left"
            :rules="rules"
          >
            <NFormItem label="权重" path="sort">
              <NInputNumber
                class="w-full"
                v-model:value="queryForm.sort"
                placeholder="请输入"
              />
            </NFormItem>
            <NFormItem>
              <div class="tools">
                <NButton
                  type="primary"
                  attr-type="button"
                  @click="handleValidateClick"
                >
                  <span>提交</span>
                </NButton>
              </div>
            </NFormItem>
          </NForm>
        </NScrollbar>
      </div>
    </div>
  </NModal>
</template>
<script setup lang="ts">
import { ref, inject } from 'vue'
import { useFullscreen } from '@vueuse/core'
import type { FormInst, FormRules } from 'naive-ui'
import {
  NButton,
  useMessage,
  NModal,
  NForm,
  NFormItem,
  NScrollbar,
  NInputNumber
} from 'naive-ui'
import routerApi from '@/service/api/router'
import MacHeader from '@/components/codeBlock/MacHeader'
const $clone = inject('$clone') as <T>(data: T) => T
const modalRef = ref()
const { isFullscreen, toggle } = useFullscreen(modalRef)
const show = ref(false)
const title = ref('添加')
const toast = useMessage()
const emit = defineEmits(['success'])
const queryForm: any = ref({
  sort: 1
})
const formRef = ref<FormInst | null>(null)
const rules: FormRules = {
  sort: [
    {
      type: 'number',
      required: true,
      message: '请输入权重',
      trigger: 'blur'
    }
  ]
}
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate(errors => {
    if (!errors) {
      save()
    }
  })
}

const save = async () => {
  if (!queryForm.value.parentId) {
    queryForm.value.parentId = 0
  }
  const params = $clone(queryForm.value)
  const { code, message } = await routerApi.sort(params)
  if (code !== 200) {
    toast.error(message)
    return
  }
  toast.success('编辑成功')
  emit('success')
  close()
}
const close = () => {
  queryForm.value = {
    sort: 1
  }
  show.value = false
}

const open = (row?: any) => {
  title.value = '添加'
  if (row) {
    queryForm.value = $clone(row)
    title.value = row?.id ? '编辑' : '添加'
  }
  show.value = true
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">
.edit-dia {
  width: 400px;
  background: #fff;
  padding: 10px;
  border-radius: 5px;
  .content {
    padding-top: 20px;
    padding-left: 5px;
  }
  .tools {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
